package cn.codesugar.demo

import org.springframework.util.ResourceUtils
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import java.io.*
import java.net.URLEncoder
import java.util.concurrent.atomic.AtomicLong
import javax.servlet.http.HttpServletResponse


@RestController
class DownloadController {

    val counter = AtomicLong()

    @RequestMapping("/download")
    fun downloading(type: String?, response: HttpServletResponse): Any {
        if (type.isNullOrEmpty()) return "type is null or empty!"
        try {
            // path是指想要下载的文件的路径
            val path = ResourceUtils.getURL("classpath:${when (type) {
                "xml" -> "get_data.xml"
                "json" -> "get_data.json"
                else -> return "$type is not exist!"
            }}").path
            if (path.isNullOrEmpty()) {
                return "path is null or empty!"
            } else {
                val file = File(path)
                println("文件地址:" + file.path)
                // 获取文件名
                val filename = file.name
                // 获取文件后缀名
                val ext = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase()
                println("文件后缀名：$ext")

                // 将文件写入输入流
                val fileInputStream = FileInputStream(file)
                val fis: InputStream = BufferedInputStream(fileInputStream)
                val buffer = ByteArray(fis.available())
                fis.read(buffer)
                fis.close()

                // 清空response
                response.reset()
                // 设置response的Header
                response.characterEncoding = "UTF-8"
                //Content-Disposition的作用：告知浏览器以何种方式显示响应返回的文件，用浏览器打开还是以附件的形式下载到本地保存
                //attachment表示以附件方式下载   inline表示在线打开   "Content-Disposition: inline; filename=文件名.mp3"
                // filename表示文件的默认名称，因为网络传输只支持URL编码的相关支付，因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"))
                // 告知浏览器文件的大小
                response.addHeader("Content-Length", "" + file.length())
                val outputStream: OutputStream = BufferedOutputStream(response.outputStream)
                response.contentType = "application/octet-stream"
                outputStream.write(buffer)
                outputStream.flush()
            }
        } catch (ex: IOException) {
            ex.printStackTrace()
        }
        return "ERROR!!!"
    }
}